package com.fingard.dsp.bank.directbank.mhcbc01;

import com.fingard.FGBiz;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.*;
import com.fingard.xml.XmlTextWriter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Alon on 2019-10-21.
 * @version 1.0
 */
public class MHCBC01Base extends DirectBase implements ITcpClient {


    protected void writeCommonHeader(XmlTextWriter xmlWriter) throws Exception {
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"GBK\"?>");
        xmlWriter.writeStartElementByAttr("edes", "<edes header=\"100\" version=\"100\" security=\"none\" lang=\"chs\">");
        xmlWriter.writeStartElement("msg-xdata");
    }

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    /**
     * 直接发送签名HTTP请求
     *
     * @param data 上送报文
     * @return 返回的报文
     */
    public String sendHttpRequestToSign(String data) {
        StringBuffer sb = new StringBuffer("");
        HttpURLConnection connection = null;
        BufferedInputStream in = null;
        BufferedOutputStream o = null;
        try {
            WriteBankLogLn2("Http 签名前报文：" + data);
            connection = (HttpURLConnection) new URL(getHttpUrlToSign()).openConnection();
            connection.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
            String tmp = String.valueOf(data.getBytes(getCharset()).length);
            WriteBankLogLn(getHttpUrlToSign() + "Http 签名报文长度:" + tmp);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Length", tmp);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            o = new BufferedOutputStream(connection.getOutputStream());
            o.write(data.getBytes(getCharset()));
            o.flush();//
            in = new BufferedInputStream(connection.getInputStream());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                //	System.out.println("Http 上送银行数据为 to sign ： 222222 len = "+len);
                sb.append(new String(buffer, 0, len, "GBK"));
                //	System.out.println("Http 上送银行数据为 to sign ： 222222 sb = "+sb.toString());
            }
        } catch (Exception e) {
            sb = new StringBuffer("-1");
            e.printStackTrace();
            WriteBankLogLn("Http 上送银行数据为 Exception getMessage ：" + e.getMessage());
        } finally {
            if (o != null) {
                try {
                    o.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        WriteBankLogLn("http通讯银行端返回的交易数据 to sign：" + sb.toString());
        return sb.toString();
    }

    public String getHttpUrlToSign() {
        StringBuffer sb = new StringBuffer("http://" + bankFront.serverIP + ":" + bankFront.signPort);
        return sb.toString();
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
        byte[] tmpBytes = p_reqStr.getBytes(getCharset());
        int XMLlength = tmpBytes.length;
        StringBuilder reqContext = new StringBuilder(p_reqStr).insert(0, String.format("%010d", XMLlength));
        String[] retStr = new String[]{"", ""};
        WriteBankUrlLogLn("请求银行的地址" + bankFront.serverIP + ":" + bankFront.serverPort);
        WriteBankLogStep2(reqContext.toString());
        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        TcpReceiver tmpReceiver = tmpClient.sendMessage(reqContext.toString().getBytes(getCharset()));
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(getCharset());
        if (retStr[1].indexOf("<edes") != -1) {
            retStr[1] = retStr[1].substring(retStr[1].indexOf("<edes"));
        } else {
            retStr[1] = retStr[1];
        }

        WriteBankLogStep3(retStr[1]);
        return retStr;

    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</edes>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
